﻿using System;
using System.Collections.Generic;
using System.Text;

namespace FieldDevice.Devices
{
    public class DeviceY3SDC : DeviceDC
    {
        public DeviceY3SDC(byte address)
            :base(address)
        {
            base.ButteryNumber = 28;
            base.Intialize();
            this.Intializes();
        }

        public const ushort System_Analoge_Value = 0x0000;                              // 读取系统模拟量
        public const ushort Register_SingleButterVoltage_Group1_Begain1 = 0x0030;       //1组1～28节电池
        public const ushort Register_SingleButterVoltage_Group1_Begain2 = 0x004C;       //1组29～56节电池
        public const ushort Register_SingleButterVoltage_Group1_Begain3 = 0x0068;       //1组57～84节电池
        public const ushort Register_SingleButterVoltage_Group1_Begain4 = 0x0084;       //1组85～112节电池
        public const ushort Register_SingleButterVoltage_Group2_Begain1 = 0x00A0;       //2组1～28节电池
        public const ushort Register_SingleButterVoltage_Group2_Begain2 = 0x00BC;       //2组29～56节电池
        public const ushort Register_SingleButterVoltage_Group2_Begain3 = 0x00D8;       //2组57～84节电池
        public const ushort Register_SingleButterVoltage_Group2_Begain4 = 0x00F4;       //2组85～112节电池

        void Intializes()
        {
            base.RequestRegister(System_Analoge_Value, 0x0014);

        }
        public override void DebugReads()
        {
            byte[] results = base.ReadRegister(Register_SingleButterVoltage_Group1_Begain1, 28);
            FieldLib.ModBusPacket request = new FieldLib.ModBusPacket(
                this.ModbusAddress, this.ModBusReadCommand,
                Register_SingleButterVoltage_Group1_Begain1, 28);
            this.TranslateRegister(request, results);
        }

        protected override float Translate(byte[] value, int begin, ushort registeraddress)
        {                        
            ushort tmpValue = value[begin];
            tmpValue <<= 8;
            tmpValue += value[begin + 1];
            if ((registeraddress >= Register_SingleButterVoltage_Group1_Begain1) && 
                registeraddress < (Register_SingleButterVoltage_Group1_Begain1 + base.ButteryNumber))
            {
                int batNo = registeraddress - Register_SingleButterVoltage_Group1_Begain1;
                float volt = tmpValue / 100.0f;
                base.ButteryVoltages[batNo] = volt;
                return volt;
            }

            switch (registeraddress)
            {
                default:
                    throw new Exception("Unhandled register " + registeraddress + "!");
            }

        }
    }
}
